package com.hm.handler.request;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.hm.handler.request.hand.AuthenticationHandler;
import com.hm.handler.request.hand.RequestRecordHandler;
import com.hm.handler.request.hand.TokenValidateHandler;

/**
 * @author shishun.wang
 * @date 2016年5月12日 下午9:53:22
 * @version 1.0
 * @describe
 */
@Component
public class RequestHandlerInterceptor implements HandlerInterceptor {

	private static Logger logger = LoggerFactory.getLogger(RequestHandlerInterceptor.class);

	@Autowired
	private RequestRecordHandler requestRecordHandler;

	@Autowired
	private AuthenticationHandler authenticationAnnotationHandler;

	@Autowired
	private TokenValidateHandler tokenValidateHandler;

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		logger.debug("---------------->postHandle2");
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		logger.debug("---------------->afterCompletion3");
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		response.setContentType("application/json");
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");

		if (handler instanceof HandlerMethod) {
			HandlerMethod method = (HandlerMethod) handler;
			boolean state = tokenValidateHandler.handler(request, response, method);// 验证token存在否
			if (state) {
				requestRecordHandler.handler(request, method);// 记录用户操作日志
				return authenticationAnnotationHandler.handler(request, response, method);
			}
			return false;
		}
		return true;
	}

}
